package zsy.test.util;

import cn.hutool.core.date.StopWatch;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangshuaiyin
 * @date 2022/7/12 15:43
 */
public class Profiler {

    private static final ThreadLocal<Long> TIME_POINTER = ThreadLocal.withInitial(System::currentTimeMillis);

    private static final ThreadLocal<StopWatch> STOP_WATCH = ThreadLocal.withInitial(StopWatch::new);

    public static void start() {
        TIME_POINTER.set(System.currentTimeMillis());
    }

    public static long stop() {
        return stop(TimeUnit.MILLISECONDS);
    }

    public static long stop(TimeUnit unit) {
        return unit.convert(System.currentTimeMillis() - TIME_POINTER.get(), TimeUnit.MILLISECONDS);
    }

    public static void begin() {
        StopWatch stopWatch = new StopWatch();
        STOP_WATCH.set(stopWatch);
        stopWatch.start();
    }

    public static long end() {
        return end(TimeUnit.MILLISECONDS);
    }

    public static long end(TimeUnit unit) {
        StopWatch stopWatch = STOP_WATCH.get();
        stopWatch.stop();
        return stopWatch.getTotal(unit);
    }

    public static void main(String[] args) {
        List<Thread> ts = new ArrayList<>(600);
        for (int j = 0; j < 1; j++) {
            Thread t = new Thread(() -> {
                for (int i = 0; i < 10; i++) {
                    try {
                        Profiler.start();
                        Profiler.begin();
                        TimeUnit.MILLISECONDS.sleep(20);
                        System.out.println("Cost1: " + Profiler.stop() + "ms");
                        System.out.println("Cost2: " + Profiler.end() + "ms");
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            ts.add(t);
        }

        Profiler.start();
        ts.forEach(Thread::start);

        // 等待所有线程执行完成
        ts.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("Total Cost: " + Profiler.stop() + "ms");
    }
}
